package cn.bjit.service.impl;

import cn.bjit.constant.CacheKey;
import cn.bjit.enums.BizCodeEnum;
import cn.bjit.exception.BizException;
import cn.bjit.interceptor.LoginInterceptor;
import cn.bjit.model.LoginUser;
import cn.bjit.request.CartItemRequest;
import cn.bjit.service.CartService;
import cn.bjit.service.ProductService;
import cn.bjit.vo.CartItemVO;
import cn.bjit.vo.CartVO;
import cn.bjit.vo.ProductVO;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CartServiceImpl implements CartService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ProductService productService;

    @Override
    public void addToCart(CartItemRequest cartItemRequest) {
        //获取当前选择要添加的那个商品
        long productId = cartItemRequest.getProductId();
        // 添加了几件
        Integer buyNum = cartItemRequest.getBuyNum();
        //获取购物车
        BoundHashOperations<String, Object, Object> boundHashOperations = getMyCartOps();

        Object cacheObj = boundHashOperations.get(productId);
        String result = "";
        if (cacheObj != null) {
            result = (String) cacheObj;
        }
        if (StringUtils.isBlank(result)) { //购物车没有 则新建一个
            CartItemVO cartItemVO = new CartItemVO();
            ProductVO productVO = productService.findDetailById(productId);
            if (productVO == null) {
                throw new BizException(BizCodeEnum.CART_FAIL);
            }
            cartItemVO.setProductId(productId);
            cartItemVO.setAmount(productVO.getAmount());
            cartItemVO.setBuyNum(buyNum);
            cartItemVO.setProductImg(productVO.getCoverImg());
            cartItemVO.setProductTitle(productVO.getTitle());

            boundHashOperations.put(productId, JSON.toJSONString(cartItemVO));

        } else {   //购物车中已经有了，则修改数量
            CartItemVO cartItem = JSON.parseObject(result, CartItemVO.class);
            cartItem.setBuyNum(cartItem.getBuyNum() + buyNum);
            boundHashOperations.put(productId, JSON.toJSONString(cartItem));
        }
    }

    /**
     * 查看购物车
     *
     * @return
     */
    public CartVO getMyCart() {
        //获取购物车项， false->是否获取最新的价格
        List<CartItemVO> cartItems = buildCartItem(true);
        CartVO cartVO = new CartVO();
        cartVO.setCartItems(cartItems);
        return cartVO;
    }

    /**
     * 删除购物车
     *
     * @param productId
     */
    public void deletItem(long productId) {
        BoundHashOperations<String, Object, Object> myCartOps = this.getMyCartOps();
        myCartOps.delete(productId);
    }

    //清空购物车
    public void clear() {
        String cartkey = this.getCartkey();
        redisTemplate.delete(cartkey);
    }

    /**
     * 修改购物车
     *
     * @param cartItemRequest
     */
    public void changeItemNum(CartItemRequest cartItemRequest) {

        BoundHashOperations<String, Object, Object> myCartOps = this.getMyCartOps();

        Object cacheObj = myCartOps.get(cartItemRequest.getProductId());
        if (cacheObj == null) {
            throw new BizException(BizCodeEnum.CART_FAIL);
        }
        String obj = (String) cacheObj;
        CartItemVO cartItemVO = JSON.parseObject(obj, CartItemVO.class);
        cartItemVO.setBuyNum(cartItemRequest.getBuyNum());
        myCartOps.put(cartItemRequest.getProductId(),JSON.toJSONString(cartItemVO));
    }

    /**
     * 获取购物车项
     *
     * @param latestPrice 是否获取最新的价格
     * @return
     */
    private List<CartItemVO> buildCartItem(boolean latestPrice) {
        //获取购物车对象
        BoundHashOperations<String, Object, Object> myCartOps = this.getMyCartOps();
        //获取到购物车中的项
        List<Object> itemList = myCartOps.values();
        //创建一个空的list集合用来添加购物车中的每个项
        List<CartItemVO> cartItemVOList = new ArrayList<>();
        //构建一个list集合,拼接id查询最新的价格
        List<Long> productIdList = new ArrayList<>();

        for (Object item : itemList) {
            CartItemVO cartItemVO = JSON.parseObject((String) item, CartItemVO.class);
            cartItemVOList.add(cartItemVO);

            productIdList.add(cartItemVO.getProductId());
        }
        if (latestPrice) {
            setProductLatestPrice(cartItemVOList, productIdList);
        }
        return cartItemVOList;
    }

    /**
     * 设置商品的最新价格
     *
     * @param cartItemVOList
     * @param productIdList
     */
    private void setProductLatestPrice(List<CartItemVO> cartItemVOList, List<Long> productIdList) {
        //批量查询
        List<ProductVO> productVOList = productService.findProductByIdBatch(productIdList);
        //分组,
        Map<Long, ProductVO> maps = productVOList.stream().collect(Collectors.toMap(ProductVO::getId, Function.identity()));
        cartItemVOList.stream().forEach(item -> {

            ProductVO productVO = maps.get(item.getProductId());
            item.setProductTitle(productVO.getTitle());
            item.setProductImg(productVO.getCoverImg());
            item.setAmount(productVO.getAmount());
        });
    }

    //获取购物车
    private BoundHashOperations<String, Object, Object> getMyCartOps() {
        String cartKey = getCartkey();
        return redisTemplate.boundHashOps(cartKey);
    }

    /**
     * 购物车的key
     * code:3
     *
     * @return
     */
    private String getCartkey() {
        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        String cartKey = String.format(CacheKey.CART_KEY, loginUser.getId());
        return cartKey;
    }

}
